<template>
  <div class="score-display">
    <div class="score-header">
      <h3>📊 Z-score标准化评分</h3>
      <button @click="calculateScores" :disabled="isCalculating" class="btn-calculate">
        {{ isCalculating ? '计算中...' : '计算评分' }}
      </button>
    </div>

    <div v-if="isCalculating" class="loading">
      <div class="spinner"></div>
      <p>正在计算评分...</p>
    </div>

    <div v-if="scoreResult && !isCalculating" class="score-content">
      <!-- 排名榜 -->
      <div class="ranking-section">
        <h4>🏆 支行排名（按综合得分）</h4>
        <div class="ranking-list">
          <div 
            v-for="(branch, index) in rankedBranches" 
            :key="branch.orgNo"
            class="ranking-item"
            :class="{ 'top-3': index < 3 }"
          >
            <div class="rank-badge" :class="'rank-' + (index + 1)">
              {{ index < 3 ? ['🥇', '🥈', '🥉'][index] : `${index + 1}` }}
            </div>
            <div class="branch-info">
              <span class="branch-name">机构号: {{ branch.orgNo }}</span>
              <span class="score-bar-container">
                <div class="score-bar" :style="{ width: branch.averageScore + '%' }"></div>
              </span>
            </div>
            <div class="score-value">
              <span class="score-number">{{ branch.averageScore }}</span>
              <span class="score-label">分</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 统计信息 -->
      <div class="statistics-section">
        <h4>📈 指标统计信息</h4>
        <div class="stats-table">
          <table>
            <thead>
              <tr>
                <th>指标名称</th>
                <th>样本数</th>
                <th>平均值</th>
                <th>标准差</th>
                <th>最小值</th>
                <th>最大值</th>
                <th>指标方向</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(stat, key) in scoreResult.statistics" :key="key">
                <td class="indicator-name">{{ stat.name }}</td>
                <td>{{ stat.count }}</td>
                <td>{{ stat.mean }}</td>
                <td>{{ stat.stdDev }}</td>
                <td>{{ stat.min.toFixed(2) }}</td>
                <td>{{ stat.max.toFixed(2) }}</td>
                <td>
                  <span class="direction-badge" :class="stat.isPositive ? 'positive' : 'negative'">
                    {{ stat.isPositive ? '↑ 正向' : '↓ 负向' }}
                  </span>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>

      <!-- 详细得分 -->
      <div class="detail-scores-section">
        <h4>🎯 支行详细得分</h4>
        <div class="branch-scores">
          <div 
            v-for="(data, orgNo) in scoreResult.branches" 
            :key="orgNo"
            class="branch-score-card"
          >
            <div class="card-header">
              <h5>机构号: {{ orgNo }}</h5>
              <div class="summary">
                <span class="rank-info">排名: {{ data.rank }}</span>
                <span class="avg-score">综合得分: {{ data.averageScore }}</span>
              </div>
            </div>
            <div class="card-body">
              <div class="indicator-scores">
                <div 
                  v-for="(score, key) in data.scores" 
                  :key="key"
                  class="indicator-score-item"
                >
                  <div class="indicator-label">
                    <span class="name">{{ score.name }}</span>
                    <span class="direction" :class="score.isPositive ? 'positive' : 'negative'">
                      {{ score.isPositive ? '↑' : '↓' }}
                    </span>
                  </div>
                  <div class="score-details">
                    <span class="original">原值: {{ score.originalValue }}</span>
                    <span class="z-score">Z: {{ score.zScore }}</span>
                    <span class="final-score" :class="getScoreClass(score.score)">
                      {{ score.score }}分
                    </span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { useScoreCalculation } from '../composables/useScoreCalculation.js'

const props = defineProps({
  scoreData: {
    type: Object,
    required: true
  },
  indicators: {
    type: Object,
    required: true
  }
})

const { calculateAllScores } = useScoreCalculation()

const isCalculating = ref(false)
const scoreResult = ref(null)

// 排名列表
const rankedBranches = computed(() => {
  if (!scoreResult.value) return []
  
  return Object.entries(scoreResult.value.branches)
    .map(([orgNo, data]) => ({
      orgNo,
      averageScore: data.averageScore,
      rank: data.rank
    }))
    .sort((a, b) => a.rank - b.rank)
})

// 计算评分
const calculateScores = () => {
  isCalculating.value = true
  
  setTimeout(() => {
    try {
      scoreResult.value = calculateAllScores(props.scoreData, props.indicators)
      console.log('[评分展示] 评分结果:', scoreResult.value)
    } catch (error) {
      console.error('[评分展示] 计算失败:', error)
    } finally {
      isCalculating.value = false
    }
  }, 100)
}

// 获取得分颜色类
const getScoreClass = (score) => {
  if (score >= 80) return 'excellent'
  if (score >= 60) return 'good'
  if (score >= 40) return 'fair'
  return 'poor'
}

// 监听数据变化，自动重新计算
watch(() => props.scoreData, () => {
  if (scoreResult.value) {
    calculateScores()
  }
}, { deep: true })
</script>

<style scoped>
.score-display {
  padding: 20px;
  background: #f5f5f5;
}

.score-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 15px 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.score-header h3 {
  margin: 0;
  color: #1a1a1a;
}

.btn-calculate {
  padding: 10px 24px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
}

.btn-calculate:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

.btn-calculate:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.loading {
  text-align: center;
  padding: 60px 20px;
  background: white;
  border-radius: 8px;
}

.spinner {
  width: 50px;
  height: 50px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #667eea;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto 20px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.score-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

/* 排名榜 */
.ranking-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.ranking-section h4 {
  margin: 0 0 15px 0;
  color: #1a1a1a;
}

.ranking-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.ranking-item {
  display: flex;
  align-items: center;
  gap: 15px;
  padding: 12px 15px;
  background: #f9f9f9;
  border-radius: 6px;
  transition: all 0.3s;
}

.ranking-item.top-3 {
  background: linear-gradient(135deg, #fff9e6 0%, #fff4d9 100%);
  border: 2px solid #ffd700;
}

.ranking-item:hover {
  transform: translateX(5px);
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.rank-badge {
  min-width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #e0e0e0;
  border-radius: 50%;
  font-weight: bold;
  font-size: 16px;
}

.rank-badge.rank-1 {
  background: linear-gradient(135deg, #ffd700 0%, #ffed4e 100%);
  font-size: 24px;
}

.rank-badge.rank-2 {
  background: linear-gradient(135deg, #c0c0c0 0%, #e8e8e8 100%);
  font-size: 24px;
}

.rank-badge.rank-3 {
  background: linear-gradient(135deg, #cd7f32 0%, #daa520 100%);
  font-size: 24px;
}

.branch-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.branch-name {
  font-weight: 500;
  color: #333;
}

.score-bar-container {
  position: relative;
  width: 100%;
  height: 8px;
  background: #e0e0e0;
  border-radius: 4px;
  overflow: hidden;
}

.score-bar {
  height: 100%;
  background: linear-gradient(90deg, #52c41a 0%, #95de64 100%);
  border-radius: 4px;
  transition: width 0.5s ease;
}

.score-value {
  display: flex;
  align-items: baseline;
  gap: 3px;
}

.score-number {
  font-size: 24px;
  font-weight: bold;
  color: #667eea;
}

.score-label {
  font-size: 14px;
  color: #999;
}

/* 统计信息 */
.statistics-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.statistics-section h4 {
  margin: 0 0 15px 0;
  color: #1a1a1a;
}

.stats-table {
  overflow-x: auto;
}

.stats-table table {
  width: 100%;
  border-collapse: collapse;
  font-size: 13px;
}

.stats-table th,
.stats-table td {
  padding: 10px;
  text-align: left;
  border: 1px solid #e8e8e8;
}

.stats-table th {
  background: #fafafa;
  font-weight: 600;
  color: #333;
}

.stats-table td {
  color: #666;
}

.stats-table tr:hover td {
  background: #f5f5f5;
}

.indicator-name {
  font-weight: 500;
  color: #333;
}

.direction-badge {
  padding: 3px 8px;
  border-radius: 3px;
  font-size: 12px;
  font-weight: 500;
}

.direction-badge.positive {
  background: #e6fffb;
  color: #00b96b;
}

.direction-badge.negative {
  background: #fff2e8;
  color: #ff7a00;
}

/* 详细得分 */
.detail-scores-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.detail-scores-section h4 {
  margin: 0 0 15px 0;
  color: #1a1a1a;
}

.branch-scores {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
  gap: 20px;
}

.branch-score-card {
  border: 1px solid #e8e8e8;
  border-radius: 6px;
  overflow: hidden;
}

.card-header {
  padding: 15px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.card-header h5 {
  margin: 0 0 8px 0;
  font-size: 16px;
}

.summary {
  display: flex;
  justify-content: space-between;
  font-size: 14px;
}

.card-body {
  padding: 15px;
  max-height: 400px;
  overflow-y: auto;
}

.indicator-scores {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.indicator-score-item {
  padding: 10px;
  background: #f9f9f9;
  border-radius: 4px;
  border-left: 3px solid #667eea;
}

.indicator-label {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 5px;
}

.indicator-label .name {
  font-weight: 500;
  color: #333;
  font-size: 13px;
}

.indicator-label .direction {
  font-size: 16px;
  font-weight: bold;
}

.indicator-label .direction.positive {
  color: #52c41a;
}

.indicator-label .direction.negative {
  color: #ff7a00;
}

.score-details {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
}

.score-details .original {
  color: #666;
}

.score-details .z-score {
  color: #999;
  font-family: monospace;
}

.score-details .final-score {
  font-weight: bold;
  font-size: 14px;
  padding: 2px 8px;
  border-radius: 3px;
}

.final-score.excellent {
  background: #e6fffb;
  color: #00b96b;
}

.final-score.good {
  background: #e6f7ff;
  color: #1890ff;
}

.final-score.fair {
  background: #fff7e6;
  color: #faad14;
}

.final-score.poor {
  background: #fff2f0;
  color: #ff4d4f;
}
</style>















